﻿namespace PillBox.Interactivity
{
    using System.Windows.Input;

    public class SwipeGotoState : SwipeGesture
    {
        protected override void OnManipulationCompleted(ManipulationCompletedEventArgs e)
        {
            base.OnManipulationCompleted(e);

            if (e.TotalManipulation.Translation.X > this.ChangeDelta)
            {
                GotoPreviousState();
            }
            else if (e.TotalManipulation.Translation.X < (this.ChangeDelta * -1))
            {
                GotoNextState();
            }
            else
            {
                GoBackToCurrentState();
            }
        }

        private void GoBackToCurrentState()
        {
            int originalIndex;
            int index;

            // store the original index
            originalIndex = index = this.CurrentStateIndex;

            // increment the index
            index++;

            // if the index is greater than the current number of states, 
            // decrement twice
            if (index > this.StateCount - 1)
            {
                index -= 2;
            }

            this.GoToState(index, this.UseTransitions);
            this.GoToState(originalIndex, this.UseTransitions);
        }

        private void GotoPreviousState()
        {
            int index = this.CurrentStateIndex - 1;

            this.GoToState(index);
        }

        private void GotoNextState()
        {
            int index = this.CurrentStateIndex + 1;

            this.GoToState(index);
        }

        private void GoToState(int index)
        {
            index = CoerceIndex(index);

            if (index == this.CurrentStateIndex)
            {
                this.GoBackToCurrentState();
            }
            else
            {
                this.GoToState(index, this.UseTransitions);
            }
        }

        private int CoerceIndex(int index)
        {
            int newIndex = index;

            if (newIndex < 0)
            {
                newIndex = 0;
            }
            else if (newIndex > this.StateCount - 1)
            {
                newIndex = this.StateCount - 1;
            }

            return newIndex;
        }
    }
}